package cn.itcast.consumer.controller;

import cn.itcast.consumer.client.UserClient;
import cn.itcast.consumer.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
//import org.springframework.cloud.netflix.ribbon.RibbonLoadBalancerClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.List;

@RestController
@RequestMapping("/consumer")
public class Controller {

//    @Autowired
//    private RestTemplate restTemplate;


//    @Autowired(required = false)
//    private DiscoveryClient discoveryClient;
//    private RibbonLoadBalancerClient client;  //Ribbon负载均衡

//    无负载均衡
/*    @GetMapping("/{id}")
    public User queryById(@PathVariable Long id){
//        String url = "http://localhost:8081/user/"+id; //固定路径

//      根据服务id得到实例
        List<ServiceInstance> instances = discoveryClient.getInstances("user-service");
//      从实例集合得到实例  根据实际判断
        ServiceInstance instance = instances.get(0);    //  负载均衡 随机 轮询 hash 统计最少访问
//从实例中取出ip与端口
        String url = "http://"+instance.getHost()+":"+instance.getPort()+"/user/"+id;
        return restTemplate.getForObject(url,User.class);
    }*/

//    负载均衡方法一
/*    @GetMapping("/{id}")
    public User queryById(@PathVariable Long id){

//      根据服务id得到负载均衡实例
        ServiceInstance instance = client.choose("user-service");//负载均衡 choose默认轮询
//从实例中取出ip与端口
        String url = "http://"+instance.getHost()+":"+instance.getPort()+"/user/"+id;
        return restTemplate.getForObject(url,User.class);
    }*/

//    @GetMapping("/{id}")
//    public User queryById(@PathVariable Long id) {
////通过@LoadBalanced负载均衡取出ip
//        String url = "http://user-service/user/" + id;//通过@LoadBalanced负载均衡
//        return restTemplate.getForObject(url, User.class);
//    }

    @Qualifier("userClient")
    @Autowired(required = false)
    private UserClient userClient;
    @GetMapping("/{id}")
    public User queryById(@PathVariable Long id) {
        return userClient.queryById(id);
    }

}
